"""
集成的产品管理视图 - 支持在产品创建/编辑时直接管理变体
"""

from rest_framework import viewsets, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view
from django.http import QueryDict
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
import json

from pecco_site.models import (
    Product, ProductVariant, ProductVariantImage, ProductOption,
    ProductOptionValue, Category
)
from ..serializers.product_integrated import (
    ProductIntegratedSerializer, VariantImageUploadSerializer
)
from ..serializers.product_new import ProductListNewSerializer
from ..filters import ProductFilter
from ..permissions import IsAdminUser


@extend_schema_view(
    list=extend_schema(summary='获取产品列表（集成）', tags=['产品管理（集成）']),
    retrieve=extend_schema(summary='获取产品详情（集成）', tags=['产品管理（集成）']),
    create=extend_schema(summary='创建产品（集成）', tags=['产品管理（集成）']),
    update=extend_schema(summary='更新产品（集成）', tags=['产品管理（集成）']),
    partial_update=extend_schema(summary='部分更新产品（集成）', tags=['产品管理（集成）']),
    destroy=extend_schema(summary='删除产品（集成）', tags=['产品管理（集成）']),
)
class ProductIntegratedViewSet(viewsets.ModelViewSet):
    """集成的产品管理 ViewSet - 支持在创建/编辑时直接管理变体"""
    queryset = Product.objects.all().prefetch_related(
        'categories', 'translations', 'variants',
        'variants__option_values', 'variants__option_values__option',
        'variants__option_values__translations', 'variants__images'
    )
    permission_classes = [IsAuthenticated, IsAdminUser]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = ProductFilter
    search_fields = ['translations__name', 'variants__sku']  # 移除 id，改用自定义搜索
    ordering_fields = ['sort_order', 'created_at', 'updated_at', 'id']
    ordering = ['sort_order', '-created_at']
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def get_queryset(self):
        """自定义查询集，支持按 ID 精确搜索"""
        queryset = super().get_queryset()
        
        # 获取搜索参数
        search_param = self.request.query_params.get('search', '').strip()
        
        if search_param:
            # 如果搜索词是纯数字，优先按 ID 精确搜索
            if search_param.isdigit():
                queryset = queryset.filter(id=int(search_param))
            # 否则使用默认的 SearchFilter（搜索名称和 SKU）
            # SearchFilter 会在 filter_queryset 中自动应用
        
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return ProductListNewSerializer
        return ProductIntegratedSerializer

    def _normalize_request_data(self, data):
        """
        处理 multipart/form-data 请求中以 JSON 字符串传递的字段，
        确保序列化器能拿到正确的 Python 数据结构。
        """
        if isinstance(data, QueryDict):
            data = data.copy()

        normalized = {}
        for key in data:
            normalized[key] = data.get(key)

        json_fields = {
            'category_slugs': [],
            'translations': {},
            'variants': []
        }
        for field, empty_value in json_fields.items():
            value = normalized.get(field)
            if value is None:
                continue
            if isinstance(value, str):
                value = value.strip()
                if value == '':
                    normalized[field] = empty_value
                    continue
                try:
                    normalized[field] = json.loads(value)
                except json.JSONDecodeError:
                    # 如果无法解析为 JSON，则保持原值，交给序列化器处理
                    normalized[field] = value
            elif isinstance(value, list) and len(value) == 1 and isinstance(value[0], str):
                # 处理 getlist 返回的 JSON 字符串列表场景
                candidate = value[0].strip()
                if candidate == '':
                    normalized[field] = empty_value
                    continue
                try:
                    normalized[field] = json.loads(candidate)
                except json.JSONDecodeError:
                    normalized[field] = value

        bool_fields = {'is_active', 'tag_new', 'tag_hot', 'tag_featured'}
        for field in bool_fields:
            if field in normalized and isinstance(normalized[field], str):
                normalized[field] = normalized[field].lower() in ('true', '1', 'on', 'yes')

        int_fields = {'sort_order'}
        for field in int_fields:
            if field in normalized and isinstance(normalized[field], str):
                try:
                    normalized[field] = int(normalized[field])
                except ValueError:
                    pass

        file_fields = {'cover_image', 'hover_image'}
        for field in list(file_fields):
            if field in normalized and not normalized[field]:
                normalized.pop(field)

        return normalized

    def create(self, request, *args, **kwargs):
        data = self._normalize_request_data(request.data)
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        data = self._normalize_request_data(request.data)
        serializer = self.get_serializer(instance, data=data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)

    @extend_schema(
        summary='获取分类列表（dog/cat）',
        tags=['产品管理（集成）'],
        responses={
            200: {
                'type': 'array',
                'items': {
                    'type': 'object',
                    'properties': {
                        'id': {'type': 'integer'},
                        'slug': {'type': 'string'},
                        'name': {'type': 'string'}
                    }
                }
            }
        }
    )
    @action(detail=False, methods=['get'])
    def categories(self, request):
        """获取分类列表（简化为 dog/cat）"""
        categories = Category.objects.filter(
            slug__in=['dog', 'cat'],
            is_active=True
        ).prefetch_related('translations')
        
        result = []
        for cat in categories:
            trans = cat.translations.filter(locale='zh').first()
            if not trans:
                trans = cat.translations.filter(locale='en').first()
            
            result.append({
                'id': cat.id,
                'slug': cat.slug,
                'name': trans.name if trans else cat.slug
            })
        
        return Response(result)

    @extend_schema(
        summary='上传变体图片',
        tags=['产品管理（集成）'],
        request={
            'multipart/form-data': {
                'type': 'object',
                'properties': {
                    'image': {'type': 'string', 'format': 'binary'},
                    'sort_order': {'type': 'integer'},
                    'is_primary': {'type': 'boolean'}
                }
            }
        },
        responses={201: {'type': 'object'}}
    )
    @action(detail=False, methods=['post'], url_path='upload-variant-image')
    def upload_variant_image(self, request):
        """
        上传变体图片（临时上传，返回URL供前端使用）
        注意：这个接口用于在创建/编辑产品时临时上传图片
        实际的图片关联会在保存产品时完成
        """
        serializer = VariantImageUploadSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
        image = serializer.validated_data['image']
        
        # 创建临时变体图片（不关联到任何变体）
        # 这里我们需要一个临时存储方案，或者直接返回上传的文件URL
        # 为了简化，我们先创建一个临时的ProductVariantImage对象
        from django.core.files.storage import default_storage
        from django.core.files.base import ContentFile
        import uuid
        
        # 生成唯一文件名
        ext = image.name.split('.')[-1]
        filename = f'temp_variants/{uuid.uuid4()}.{ext}'
        
        # 保存文件
        path = default_storage.save(filename, ContentFile(image.read()))
        url = default_storage.url(path)
        
        # 返回完整URL
        if request:
            full_url = request.build_absolute_uri(url)
        else:
            full_url = url
        
        return Response({
            'url': full_url,
            'path': path
        }, status=status.HTTP_201_CREATED)

    @extend_schema(
        summary='批量删除产品',
        tags=['产品管理（集成）'],
        request={
            'application/json': {
                'type': 'object',
                'properties': {
                    'ids': {
                        'type': 'array',
                        'items': {'type': 'integer'}
                    }
                }
            }
        }
    )
    @action(detail=False, methods=['post'])
    def bulk_delete(self, request):
        """批量删除产品"""
        ids = request.data.get('ids', [])
        if not ids:
            return Response(
                {'error': '请提供要删除的产品 ID'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        deleted_count, _ = Product.objects.filter(id__in=ids).delete()
        return Response({
            'message': f'成功删除 {deleted_count} 个产品',
            'deleted_count': deleted_count
        })

    @extend_schema(
        summary='切换产品激活状态',
        tags=['产品管理（集成）']
    )
    @action(detail=True, methods=['patch'])
    def toggle_active(self, request, pk=None):
        """切换产品激活状态"""
        product = self.get_object()
        product.is_active = not product.is_active
        product.save()
        return Response({'is_active': product.is_active})

    @extend_schema(
        summary='获取可用的选项类型',
        tags=['产品管理（集成）'],
        responses={
            200: {
                'type': 'array',
                'items': {
                    'type': 'object',
                    'properties': {
                        'option_type': {'type': 'string'},
                        'display_name': {'type': 'string'}
                    }
                }
            }
        }
    )
    @action(detail=False, methods=['get'])
    def option_types(self, request):
        """获取可用的选项类型"""
        option_types = [
            {'option_type': 'size', 'display_name': '规格'},
            {'option_type': 'color', 'display_name': '颜色'},
            {'option_type': 'material', 'display_name': '材质'},
            {'option_type': 'other', 'display_name': '其他'},
        ]
        return Response(option_types)
